package vn.com.bookstore.adapter;

import java.util.ArrayList;

import vn.com.bookstore.Config;
import vn.com.bookstore.R;
import vn.com.bookstore.model.Book;
import vn.com.bookstore.model.Page;
import vn.com.bookstore.util.lazzyloading.ImageLoader;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ChapterAdapter extends BaseAdapter {
	Context context;
	Book book;

	public ChapterAdapter(Context context, Book book) {
		this.context = context;
		this.book = book;
	}

	public void setData(Book book) {
		if (book.pages == null)
			book.pages = new ArrayList<Page>();
		this.book = book;
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return book.pages.size();
	}

	@Override
	public Object getItem(int position) {
		return book.pages.get(position);
	}

	@Override
	public long getItemId(int position) {
		return book.pages.get(position).page;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			ChapterHolder holder = new ChapterHolder(context);
			convertView = holder.parent;
			convertView.setTag(holder);
		}
		ChapterHolder holder = (ChapterHolder) convertView.getTag();
		holder.setData(book.pages.get(position));

		return holder.parent;
	}

	public class ChapterHolder {
		View parent;
		ImageView avatar;
		TextView title, sample;
		ImageView bookMark;

		public ChapterHolder(Context context) {
			parent = View.inflate(context, R.layout.item_chapter, null);
			avatar = (ImageView) parent.findViewById(R.id.avatar);
			title = (TextView) parent.findViewById(R.id.title);
			sample = (TextView) parent.findViewById(R.id.sample);
			bookMark = (ImageView) parent.findViewById(R.id.bookmark);
		}

		public void setData(Page page) {
			title.setText(context.getString(R.string.page) + " " + page.page + ": " + page.title);
			String txt = "";
			if (page.isImage()) {
				txt = page.title;
				sample.setVisibility(View.GONE);
			} else {
				sample.setVisibility(View.VISIBLE);
				try {
					if (page.content != null)
						txt = page.content + "...";
					else
						txt = "...";
				} catch (Exception e) {
					txt = page.page + ": " + page.content;
				}
			}
			sample.setText(txt.replaceAll("\\<.*?>", ""));
			ImageLoader loader = new ImageLoader(context);
			String urlImage = Config.getUrlImage(book.image);
			loader.DisplayImage(urlImage, avatar);
			bookMark.setVisibility(page.bookMark ? View.VISIBLE : View.GONE);
		}
	}
}
